<template> 
  <div>
    <el-upload action="http://up-z2.qiniup.com" :data="dataObj" list-type="picture" :multiple="false"
      :show-file-list="showFileList" :file-list="fileList" :before-upload="beforeUpload" :on-remove="handleRemove"
      :on-success="handleUploadSuccess" :on-preview="handlePreview">
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10MB</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="fileList[0].url" alt="">
    </el-dialog>
  </div>
</template>
<script>
  import { policy } from './policy'
  import { getUUID } from '@/utils'
  import * as qiniu from "qiniu-js";

  export default {
    name: 'singleUpload',
    props: {
      value: String
    },
    computed: {
      imageUrl() {
        return this.value;
      },
      imageName() {
        if (this.value != null && this.value !== '') {
          return this.value.substr(this.value.lastIndexOf("/") + 1);
        } else {
          return null;
        }
      },
      fileList() {
        return [{
          name: this.imageName,
          url: this.imageUrl
        }]
      },
      showFileList: {
        get: function () {
          return this.value !== null && this.value !== '' && this.value !== undefined;
        },
        set: function (newValue) {
        }
      }
    },
    data() {
      return {
        dataObj: {
          // policy: '',
          // signature: '',
          // key: '',
          // ossaccessKeyId: '',
          // dir: '',
          // host: '',
          // // callback:'',
          token: '',
          url: '',
          dirPrefix: '',
          timePrefix: ''
        },
        dialogVisible: false,
        url: ''

      };
    },
    methods: {
      qiniuUp(file, _self) {
        console.log("qiniu上传", _self.dataObj);
        // 七牛token
        var qiniuToken = _self.dataObj.token
        var fileName = file.name;
        // 获取文件后缀名 .jpg
        var suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length)
        // console.log("文件信息：",fileName,suffix)
        // 获取文件大小 单位KB
        var size = (file.size / 1024).toFixed(2)
        // console.log("文件信息：",fileName,suffix,size)

        // 设置上传的七牛key 上传成功需要把这个值提交到后台
        var bucketToken = _self.dataObj.dirPrefix + '/' + _self.dataObj.timePrefix + getUUID() + suffix
        this.fileName = bucketToken
        // console.log("文件信息2：", fileName, suffix, size, bucketToken)
        this.url = _self.dataObj.url + '/' + bucketToken
        console.log("url", this.url)
        // console.log("骑牛信息", file, bucketToken, qiniuToken, putExtra, config)

        console.log("bucketToken 地址", bucketToken)
        // 实例化七牛云的上传实例
        var observable = qiniu.upload(file, bucketToken, qiniuToken, putExtra, config);
        console.log("observable" + observable)

        // 设置实例的监听对象
        var observer = {
          //上传过程的监听函数 result参数带有total字段的 object，包含loaded、total、percent三个属性)
          next(result) {
            // 实现上传进度条 ... 
            console.log(result)
          },
          //上传失败回调
          error(err) {
            console.log("失败", err.message)
          },
          // 上传完成回调
          complete(res) {
            // 提交数据给后端同事等业务逻辑 ....
            console.log("成功", res)
          }
        };
        var putExtra = {
          //原文件名
          fname: "",
          //用来放置自定义变量
          params: {},
          //限制上传文件类型 null || []
          mimeType:  ["image/png", "image/jpeg", "image/gif"]
        };
        var config = {
          //存储区域(z0:代表华东;z2:代表华南,不写默认自动识别)
          region: qiniu.region.z2,
          //分片上传的并发请求量
          concurrentRequestLimit: 2
        };

        // console.log("qiniu"+qiniu.upload)
        // console.log("file"+file)
        // console.log("bucketToken"+bucketToken)
        // console.log("qiniuToken"+qiniuToken)
        // console.log("putExtra"+putExtra)
        // console.log("config"+config)

        // 上传开始
        var subscription = observable.subscribe(observer);
        // 取消上传
        // subscription.unsubscribe();
        console.log("end", subscription)

      },

      emitInput(val) {
        this.$emit('input', val)
      },
      handleRemove(file, fileList) {
        this.emitInput('');
      },
      handlePreview(file) {
        this.dialogVisible = true;
      },
      beforeUpload(file) {
        let _self = this;
        return new Promise((resolve, reject) => {
          policy().then(response => {
            console.log("响应的数据", response);
            // _self.dataObj.policy = response.data.policy;
            // _self.dataObj.signature = response.data.signature;
            // _self.dataObj.ossaccessKeyId = response.data.accessid;
            // _self.dataObj.key = response.data.dir + getUUID() + '_${filename}';
            // _self.dataObj.dir = response.data.dir;
            // _self.dataObj.host = response.data.host;

            _self.dataObj.token = response.data.token;
            _self.dataObj.url = response.data.url;
            _self.dataObj.dirPrefix = response.data.dirPrefix;
            _self.dataObj.timePrefix = response.data.timePrefix;

            console.log("响应的数据222。。。", _self.dataObj);

            this.qiniuUp(file, _self);



            resolve(true)
            console.log("beforeUpload end");

          }).catch(err => {
            reject(false)
          })
        })
      },

      handleUploadSuccess(res, file) {
        console.log("上传成功...")
        this.showFileList = true;
        this.fileList.pop();
        this.fileList.push({ name: file.name, url: this.url });
        this.emitInput(this.fileList[0].url);
      }
    }
  }
</script>
<style>

</style>